<template>
  <div>
    <div v-if="fileList.length > 0" class="el-image-box">
      <div v-if="isImg == 1">
        <el-image
          v-for="v in fileList"
          :key="v.ossId"
          class="el-image"
          :src="v.url"
          fit="cover"
          :preview-src-list="srcList"
        ></el-image>
      </div>
      <div v-if="isImg == 2">
        <!-- 文件列表 -->
        <transition-group
          class="upload-file-list el-upload-list el-upload-list--text"
          name="el-fade-in-linear"
          tag="ul"
        >
          <li
            :key="file.url"
            class="el-upload-list__item ele-upload-list__item-content"
            v-for="file in fileList"
          >
            <el-link :href="`${file.url}`" :underline="false" target="_blank">
              <span class="el-icon-document">
                {{ getFileName(file.name) }}
              </span>
            </el-link>
          </li>
        </transition-group>
      </div>
    </div>

    <span v-else> 暂无数据</span>
  </div>
</template>

<script>
import { listByIds } from "@/api/system/oss";

export default {
  props: {
    value: [String, Object, Array],
    isImg: [String, Number], // 1图片 ， 2 文件
  },
  data() {
    return {
      fileList: [],
      srcList: [],
    };
  },
  watch: {
    value: {
      async handler(val) {
        if (val) {
          // 首先将值转为数组
          let list;
          if (Array.isArray(val)) {
            list = val;
          } else {
            await listByIds(val).then((res) => {
              list = res.data;
            });
          }
          // 然后将数组转为对象数组
          this.fileList = list.map((item) => {
            // 此处name使用ossId 防止删除出现重名
            item = {
              name: item.ossId,
              url: item.url,
              ossId: item.ossId,
              fileName: item.originalName,
            };
            return item;
          });

          this.srcList = list.map((item) => {
            return item.url;
          });
        } else {
          this.fileList = [];
          this.srcList = [];
          return [];
        }
      },
      deep: true,
      immediate: true,
    },
  },
  computed: {},
  created() {},
  methods: {
    // 获取文件名称
    getFileName(name) {
      // 如果是url那么取最后的名字 如果不是直接返回
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
      } else {
        return name;
      }
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        if (list[i].ossId) {
          strs += list[i].ossId + separator;
        }
      }
      return strs != "" ? strs.substr(0, strs.length - 1) : "";
    },
  },
};
</script>
<style lang="scss" scoped>
.el-image-box {
  .el-image {
    border: 1px solid #c0ccda;
    border-radius: 6px;
    width: 102px;
    height: 102px;
    margin-right: 8px;
    margin-bottom: 8px;
  }
}
</style>

